<template>
  <!-- 用户列表 -->
  <!-- <mydialog  v-model="addUserDialogVisible" :height='600'></mydialog> -->
  <!-- <mydialog
    transition="top"
    title="新增信息"
    :btn="1"
    :showModule="addUserDialogVisible"
    submitBtn="确定"
    cancelBtn="取消"
    @cancel="addUserDialogVisible = false"
    @submit="submit"
    themeColor="#ff6600"
  >
    <template v-slot:body>
      <div>......</div>
    </template>
  </mydialog> -->
  <!-- <el-table
    row-key="id"
      :data="tableData"
      stripe
      style="
        width: 100%;
        --el-table-border-color: none;
        border-right: 1px #143275 solid;
        border-left: 1px #143275 solid;
        border-bottom: 1px #143275 solid;
      "
      :highlight-current-row="false"
      :header-cell-style="{
        backgroundColor: '#173750',
        color: '#ffffff',
        textAlign: 'center',
        borderLeft: '0.5px #154480 solid',
        borderBottom: '1px #154480 solid',
      }"
      :cell-style="{
        color: '#fff',
        fontSize: '14px',
        textAlign: 'center',
        borderBottom: '0.5px #143275 solid',
        borderLeft: '0.5px #143275 solid',
      }"
      :row-style="{ color: '#fff', fontSize: '14px', textAlign: 'center' }"
      :row-class-name="tableRowClassName"
      empty-text="暂无数据"
      max-height="818"
    > -->
  <div class="user-lists">
    <div class="top">
      <div class="search">
        <div class="username">
          <span class="utitle">登录账户</span>
          <el-input
            @change="searchClick"
            clearable
            v-model="userinfo.userName"
            placeholder="请输入用户名称"
          />
          <el-button class="sear-btn" @click="searchClick" :loading="loading"
            >查询</el-button
          >
        </div>
        <div class="username">
          <span class="rtitle">角色名称</span>
          <el-select
            v-model="userinfo.role"
            placeholder="请选择角色"
            clearable
            @change="searchClick"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in roles"
              :key="item.id"
            />
          </el-select>
        </div>
      </div>
      <div class="add">
        <!-- <input type="file" @change="handleFileUpload" /> -->
        <el-button @click="handExport">导出用户</el-button>
        <el-button @click="handImport">导入用户</el-button>
        <el-button @click="addUserBtnClick">添加用户</el-button>
      </div>
    </div>
    <div class="title">用户列表</div>
    <div class="user-list">
      <el-table
        v-loading="loading1"
        element-loading-text="加载中"
        row-key="id"
        :data="tableData"
        stripe
        style="width: 100%"
        :highlight-current-row="true"
        :header-cell-style="{
          backgroundColor: '#173750',
          color: '#ffffff',
          textAlign: 'center',
        }"
        :cell-style="{
          color: '#fff',
          fontSize: '14px',
          textAlign: 'center',
        }"
        :row-style="{ color: '#fff', fontSize: '14px', textAlign: 'center' }"
        :row-class-name="tableRowClassName"
        empty-text="暂无数据"
      >
        <el-table-column
          :prop="item.prop"
          :label="item.name"
          v-for="item in column"
          :key="item.prop"
        >
          <template #default="scope">
            <div
              v-if="item.prop == 'status'"
              :style="{
                color:
                  scope.row.status == 1
                    ? ' #18FFAE'
                    : scope.row.status == 2
                    ? 'red'
                    : 'yellow',
              }"
            >
              {{
                scope.row.status == 1
                  ? "在线"
                  : scope.row.status == 2
                  ? "离线"
                  : "挂机"
              }}
            </div>

            <div v-if="item.prop == 'role'">
              {{ getRoleNameById(scope.row.role) }}
            </div>

            <div v-if="item.prop == 'division'">
              {{ getdivisionNameById(scope.row.role) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <span class="update" @click.prevent="updateUser(row)"> 编辑 </span>
            <span class="del" @click.prevent="deleteUser(row)"> 删除 </span>
          </template>
        </el-table-column>
      </el-table>
      <div class="fy">
        <el-pagination
          v-model:current-page.number="userinfo.currentPage"
          v-model:page-size="userinfo.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total,  prev, pager, next, "
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <el-dialog
    v-model="addUserDialogVisible"
    :title="addUserTitle"
    width="500"
    :before-close="handleClose"
  >
    <div>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="addUserRuleForm"
        :rules="addUserRules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="登录账户" prop="userName" :error="errorMsg1">
          <el-input
            v-model="addUserRuleForm.userName"
            clearable
            @blur="checkMobile"
          />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="addUserRuleForm.password" clearable />
        </el-form-item>
        <el-form-item label="用户姓名" prop="name">
          <el-input v-model="addUserRuleForm.name" clearable />
        </el-form-item>
        <el-form-item label="部门" prop="division">
          <el-select
            clearable
            v-model="addUserRuleForm.division"
            placeholder="请选择部门"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in divisionList"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-select
            clearable
            v-model="addUserRuleForm.role"
            placeholder="请选择角色"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in roles"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="addUser(ruleFormRef)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  
  <el-dialog
    title="用户导入"
    :visible.sync="show"
    width="25%"
    :before-close="handleClose"
    v-model="show"
  >
    <div class="updatediv">
      <el-upload
        class="upload-demo"
        :on-remove="handleRemove"
        :on-change="onChange"
        :file-list="fileList"
        :limit="1"
        :auto-upload="false"
        accept=".xlsx,.doc,.xls"
        drag
        action="#"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          只能上传1个文件，且不超过500kb
        </div>
      </el-upload>
      <progressBar
        ref="progressBarRef"
        v-model:progressBarIshow="progressBarIshow"
        @close="progressBarClose"
      ></progressBar>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="upload">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
const progressBarIshow = ref(false);
import progressBar from "@/components/progressBar";
import { ElMessage, ElMessageBox } from "element-plus";
import * as XLSX from "xlsx";
// import FileSaver from "file-saver";
import exportExcel from "@/utils/exportExcel";
defineOptions({
  name: "user", //组件命名
});
import {
  getUserListAPI,
  addUserAPI,
  userCheckAPI,
  uploadUserAPI,
  delUserAPI,
} from "@/api/user";
const props = defineProps({
  activeTab: {
    type: Number,
    default: 0,
  },
});
import { uploadAPI } from "@/api/home";
const submit = () => {
  addUserDialogVisible.value = false;
};
import { ref, onMounted, onUnmounted, inject } from "vue";
import { useRoute, useRouter } from "vue-router";
import mydialog from "@/components/dialog";

const userinfo = ref({
  userName: "",
  role: null,
  currentPage: 1,
  pageSize: 13,
});
// 角色列表
const roles = ref([
  {
    name: "管理员",
    id: 1,
  },
  {
    name: "运维",
    id: 2,
  },
  {
    name: "指导员",
    id: 3,
  },
  {
    name: "参谋",
    id: 4,
  },
  {
    name: "成员",
    id: 5,
  },
]);
// 获取角色名称
function getRoleNameById(id) {
  let name = roles.value.filter((v) => v.id == id)[0].name;
  return name;
}
const loading1 = ref(false);
const loading = ref(false);
const searchClick = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 120);
  getUserList();
};

const column = [
  {
    name: "登录账号",
    prop: "userName",
  },
  {
    name: "登录密码",
    prop: "password",
  },
  {
    name: "用户编号",
    prop: "userNum",
  },
  {
    name: "用户姓名",
    prop: "name",
  },
  {
    name: "部门",
    prop: "division",
  },
  {
    name: "角色",
    prop: "role",
  },
  {
    name: "状态",
    prop: "status",
  },
];
const tableData = ref([]);
// 获取用户列表
const getUserList = async () => {
  loading1.value = true;

  try {
    let res = await getUserListAPI(userinfo.value);
    console.log(res, "用户列表");
    tableData.value = res.data.data;
    total.value = res.data.total;
    loading1.value = false;
  } catch (error) {
    console.log(error);
  }
};

function tableRowClassName({ row, rowIndex }) {
  if (rowIndex % 2 === 0) {
    // 第一行特殊处理
    return "first-row";
  } else {
    // 第二行特殊处理
    return "warning-row";
  }
  return "";
}
const currentPage = ref(1);
const pageSize = ref(13);
const total = ref(0);
total.value = tableData.value.length;
const screen = ref({
  height: window.innerHeight,
  width: window.innerWidth,
});
// 每页几条
const handleSizeChange = (val) => {
  console.log(val);

  getUserList();
};

// 第几页
const handleCurrentChange = (val) => {
  // console.log(val);
  // console.log(currentPage.value);

  userinfo.value.currentPage = val;
  getUserList();
};

// 添加用户弹框
const addUserDialogVisible = ref(false);
const addUserTitle = ref("");
const addUserBtnClick = () => {
  addUserTitle.value = "添加用户";
  addUserDialogVisible.value = true;
};
const handleClose = () => {
  ElMessageBox.confirm("确定关闭弹框?")
    .then(() => {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.resetFields();
      addUserDialogVisible.value = false;
    })
    .catch(() => {
      // catch error
    });
};
const ruleFormRef = ref(null);
const addUserRuleForm = ref({});
const addUserRules = {
  userName: [
    { required: true, message: "请输入登录账户", trigger: "blur" },
    // { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" },
  ],
  password: [{ required: true, message: "请输入登录账户", trigger: "blur" }],
  name: [{ required: true, message: "请输入用户姓名", trigger: "blur" }],

  division: [
    {
      required: true,
      message: "请选择部门",
      trigger: "change",
    },
  ],
  role: [
    {
      required: true,
      message: "请选择角色",
      trigger: "change",
    },
  ],
};
// 部门列表
const divisionList = ref([
  {
    name: "xx1部",
    id: 1,
  },
  {
    name: "xx2部",
    id: 2,
  },
  {
    name: "xx3部",
    id: 3,
  },
  {
    name: "xx4部",
    id: 4,
  },
]);
// 获取部门名称
// 获取角色名称
function getdivisionNameById(id) {
  let name = divisionList.value.filter((v) => v.id == id)[0].name;
  return name;
}
// 校验用户名是否已被占用
// 添加/编辑用户校验手机号码是否重复
const errorMsg1 = ref("");
async function checkMobile() {
  errorMsg1.value = ""; //校验前需情况错误信息
  if (addUserRuleForm.value.userName != "") {
    let res = await userCheckAPI({ userName: addUserRuleForm.value.userName });
    console.log(res, 888);
    if (res.data.respDesc) {
      errorMsg1.value = ""; //后台返回错误信息
    } else {
      errorMsg1.value = "该账号已被注册"; //后台返回错误信息
    }
  }
}
//
const addUser = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log("submit!");
      let res = await addUserAPI(addUserRuleForm.value);
      getUserList();
      addUserDialogVisible.value = false;
      formEl.resetFields();
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 编辑用户
const updateUser = (row) => {
  addUserTitle.value = "编辑用户";
  addUserRuleForm.value = row;
  addUserDialogVisible.value = true;
};

// 删除用户
const deleteUser = (row) => {
  try {
    ElMessageBox.confirm("确定删除此用户?")
      .then(async () => {
        let res = await delUserAPI({ id: row.id });
        console.log(res);
        getUserList();
        ElMessage({
          showClose: true,
          message: res.message,
          type: "success",
        });
      })
      .catch(() => {
        ElMessage({
          showClose: true,
          message: "已取消删除",
          type: "info",
        });
      });
  } catch (error) {
    console.log(error);
  }
};
// 导出
const handExport = () => {
  // const data = XLSX.utils.json_to_sheet(tableData.value); //此处tableData.value为表格的数据
  // const wb = XLSX.utils.book_new();
  // XLSX.utils.book_append_sheet(wb, data, "test-data"); //test-data为自定义的sheet表名
  // XLSX.writeFile(wb, "test.xlsx"); //test.xlsx为自定义的文件名

  const titleArr = column.map((v) => v.name);
  //表头第一行从左到右
  const fields = column.map((v) => v.prop);
  exportExcel(tableData.value, "用户列表", titleArr, "sheetName", fields); //列表变量名、文件名、第一行标题、表名、字段名
};

//导入
const handImport = () => {
  show.value = true;
};

const show = ref(false);
const fileList = ref([]);
//存储上传的文件列表
function onChange(file, fileList1) {
  fileList.value = fileList1;
}
//存储移除后的文件列表
function handleRemove(file, fileList) {
  fileList.value = fileList;
}

const progressBarClose = (e) => {
  show.value = false;
  getUserList();
  ElMessage({
    showClose: true,
    message: updateMessage,
    type: "success",
  });
};
//确认上传
const progressBarRef = ref(null);
let updateMessage = "";
async function upload() {
  progressBarIshow.value = true;
  if (fileList.value[0].raw) {
    let fileFormData = new FormData();
    let fileName = fileList.value[0].name;
    // console.log(fileList.value[0]);
    fileFormData.append("myfile", fileList.value[0].raw, fileName); //filename是键，file是值，就是要传的文件，test.zip是要传的文件名
    let requestConfig = {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    };
    let res = await uploadUserAPI(fileFormData);
    console.log(progressBarRef.value);
    progressBarRef.value.move();
    updateMessage = res.data.message;

    //如果存在文件则设置文件类型
    // if (
    //   fileList.value[0].raw.type ==
    //     "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    //   fileList.value[0].raw.type == "application/vnd.ms-excel"
    // ) {
    //   importfxx(fileList.value[0].raw); //importfxx()为获取并处理文件数据函数
    // } else {
    //   ElMessage({
    //     showClose: true,
    //     message: "附件格式错误，请删除后重新上传！",
    //     type: "warning",
    //   });
    // }
  }
}

function importfxx(obj) {
  console.log(obj);

  var rABS = false; //是否将文件读取为二进制字符串
  var f = obj;

  var reader = new FileReader();
  //if (!FileReader.prototype.readAsBinaryString) {
  FileReader.prototype.readAsBinaryString = function (f) {
    var binary = "";
    var rABS = false; //是否将文件读取为二进制字符串
    var wb; //读取完成的数据
    var outdata;
    var reader = new FileReader();
    reader.onload = function (e) {
      var bytes = new Uint8Array(reader.result);
      var length = bytes.byteLength;
      for (var i = 0; i < length; i++) {
        binary += String.fromCharCode(bytes[i]);
      }

      if (rABS) {
        wb = XLSX.read(btoa(fixdata(binary)), {
          //手动转化
          type: "base64",
        });
      } else {
        wb = XLSX.read(binary, {
          type: "binary",
        });
      }
      outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
      console.log("上传的数据:", outdata);
      //此处可对数据进行处理
      let arr = [];
      outdata.map((v) => {
        let obj = {};

        column.forEach((s) => {
          obj[s.prop] = v[s.name];
        });

        // obj.id = v['序号']

        arr.push(obj);
      });

      if (arr.length > 0) {
        ElMessage({
          showClose: true,
          message: "上传成功！",
          type: "success",
        });
      }
      show.value = false;
      // _this.list = _this.list.concat(arr); //合并原有数组
      console.log(arr);
      tableData.value.unshift(...arr);
      return arr;
    };
    reader.readAsArrayBuffer(f);
  };
  if (rABS) {
    reader.readAsArrayBuffer(f);
  } else {
    reader.readAsBinaryString(f);
  }
}

//
const isFullscreen = ref(false);

// 全屏监听
function onresize(event) {
  // 利用屏幕分辨率和window对象的内高度来判断兼容IE
  let winFlag = window.innerHeight === window.screen.height - 1;

  // 利用window全屏标识来判断 -- IE无效
  let isFull = window.fullScreen || document.webkitIsFullScreen;

  if (isFull === undefined) {
    isFullscreen.value = winFlag;
  } else {
    isFullscreen.value = winFlag || isFull;
  }
  console.log(winFlag); // true全屏   false不是全屏
  if (winFlag) {
    userinfo.value.pageSize = 16;
  } else {
    userinfo.value.pageSize = 13;
  }
  getUserList();
}

onMounted(() => {
  window.addEventListener("resize", onresize);
  getUserList();
});
</script>
<style scoped lang="scss">
@keyframes move {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(0);
  }
}

.user-lists {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  color: #fff;
  animation: move 0.2s linear;
  overflow: hidden;
  .top {
    display: flex;
    justify-content: space-between;
    height: 40px;

    .search {
      display: flex;
      height: 40px;

      .username {
        margin-right: 30px;
        padding: 5px 0;
        height: 30px;
        height: 100%;
        line-height: 30px;
        .utitle {
          //   margin-right: 10px;

          width: 140px;
          display: inline-block;
        }
        .rtitle {
          width: 100px;
        }
        .sear-btn {
          height: 30px;
          border-color: transparent;
          border-radius: 0;
          background: #6aa3ce;
          color: #fff;
        }

        :deep() {
          .el-input__wrapper {
            width: 100px;
            border-radius: 0;
            background: transparent;
            box-shadow: none;

            border: 1px solid #008aaf !important;
          }
          .el-input__inner {
            color: #fff;
          }
          .el-input {
            height: 30px;
            border-radius: 0;
            border: 1px solid #008aaf;
            border: 0;
            .el-input.is-focus {
              .el-input__wrapper {
                // box-shadow: 0 0 0 1px transparent inset !important;
                background: red;
                border: 1px solid red !important;
              }
            }
          }

          .el-select__wrapper {
            width: 180px !important;
            background-color: transparent !important;
            box-shadow: none;
            border: 1px solid #008aaf !important;
          }
          .el-select__selected-item {
            color: #fff !important;
          }
          .is-transparent {
            color: #ccc !important;
          }
          //   input:focus {
          //     width: 160px;
          //     border: 2px solid red;
          //     border-color: red !important; /* 改变为蓝色 #409EFF */
          //   }
        }

        display: flex;
      }
    }
    .add {
      .el-button {
        background: #609ab3;
        color: #fff;
        width: 100px;
        height: 40px;
      }
    }
  }
  .title {
    margin: 10px 0;
    width: 100%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    background: linear-gradient(
      270deg,
      rgba(13, 19, 30, 1) 0%,
      rgba(53, 139, 155, 1) 50%,
      rgba(20, 32, 54, 1) 100%
    );
  }
  .user-list {
    width: 100%;
    height: calc(100% - 40px - 60px);
    // border: 1px solid red;
  }

  .fy {
    margin-top: 10px;
    height: 30px;
  }
}

:deep() {
  .el-table__expand-icon > .el-icon {
    display: none !important;
  }
  .el-loading-mask {
    background: transparent;
  }

  .el-table__header .cell {
    padding: 0 !important;
    text-overflow: unset !important;
    white-space: nowrap !important;
  }

  .cell:empty::after {
    content: "--" !important;
  }

  .el-table {
    border: none;
    --el-table-border-color: 0;

    font-size: 12px;

    height: 94% !important;
  }

  .el-table--fit {
    background: transparent;
  }

  .el-table__inner-wrapper {
    border: none;
  }

  .el-table tr {
    color: #fff;
    height: 20px;
    background: #1e292b;
  }

  .cell {
    white-space: nowrap;
  }

  .el-table td.el-table__cell,
  .el-table th.el-table__cell.is-leaf {
    // border-bottom: 1px solid #00ff3f;
  }

  .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
    background: #121d1f;
  }

  .el-table--striped .el-table__body tr.el-table__row--striped td {
    background: rgba(255, 255, 255, 0.05);
  }
  .el-table__body tr.current-row > td {
    background-color: #15c0ff20 !important;
  }

  .el-scrollbar {
    // 横向滚动条
    .el-scrollbar__bar.is-horizontal .el-scrollbar__thumb {
      opacity: 1; // 默认滚动条自带透明度
      height: 8px; // 横向滑块的宽度
      border-radius: 2px; // 圆角度数
      // background-color: rgba(136, 219, 255, 1); // 滑块背景色
      background-color: #3f474d; // 滑块背景色
      box-shadow: 0 0 6px rgba(0, 0, 0, 0.15); // 滑块阴影
    }

    // 纵向滚动条
    .el-scrollbar__bar.is-vertical .el-scrollbar__thumb {
      opacity: 1;
      width: 8px; // 纵向滑块的宽度
      border-radius: 2px;
      // background-color: rgba(136, 219, 255, 1);
      background-color: #3f474d;
      box-shadow: 0 0 6px rgba(0, 0, 0, 0.15);
    }
  }

  // 分页

  .el-pagination button {
    background: rgba(18, 157, 177, 0.5);
    color: #fff;
  }

  .el-pager {
    li {
      background: rgba(18, 157, 177, 0.5);
      color: #fff;
      // padding-left: 20px;
      // padding-right: 20px;
      // padding-top: 5px;
      // padding-bottom: 5px;
      margin: 0 3px;
    }

    .is-active {
      color: red;
    }
  }
  .update {
    border-width: 0px;
    display: inline-block;
    width: 54px;
    height: 32px;
    line-height: 32px;
    background: inherit;
    background-color: rgba(24, 95, 117, 1);
    box-sizing: border-box;
    border-width: 2px;
    border-style: solid;
    border-color: rgba(0, 199, 163, 1);
    border-radius: 0px;
    color: #fff;
    font-size: 12px;
    &:hover {
      background: #009aa4;
    }
  }
  .del {
    margin-left: 5px;
    border-width: 0px;
    display: inline-block;

    width: 54px;
    height: 32px;
    line-height: 32px;
    background: inherit;
    background-color: rgba(255, 255, 255, 0.2);
    box-sizing: border-box;
    border-width: 2px;
    border-style: solid;
    border-color: rgba(255, 72, 72, 1);
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    font-family: "DengXian Regular", "DengXian";
    font-weight: 400;
    font-style: normal;
    font-size: 16px;
    color: #ff4848;
  }

  .demo-ruleForm {
    // .el-input__wrapper {
    //   // background: rgba(18, 157, 177, 0.5);
    //   background: #175f80;

    //   .el-input__inner {
    //     color: #fff;
    //   }

    //   .el-icon {
    //     color: #fff;
    //   }
    // }
  }
}
.updatediv {
  position: relative;
  height: 200px;
  overflow: hidden;

  .upload-demo {
  }
}
</style>
